﻿/// <summary>
/// https://leetcode-cn.com/problems/longest-palindromic-substring/
/// </summary>
public class Solution
{
    public string LongestPalindrome(string s)
    {
        System.Text.StringBuilder result = new();
        for (int i = 0; i < s.Length - result.Length / 2; i++)
        {
            char si = s[i];
            {
                System.Text.StringBuilder stringBuilder = new();
                _ = stringBuilder.Append(si);
                for (int d = 1; i - d >= 0 && i + d < s.Length; d++)
                {
                    char c = s[i - d];
                    if (c == s[i + d])
                    {
                        _ = stringBuilder.Insert(0, c).Append(c);
                    }
                    else
                        break;
                }
                result = result.Length > stringBuilder.Length ? result : stringBuilder;
            }

            if (i - 1 >= 0 && s[i - 1] == si)
            {
                System.Text.StringBuilder stringBuilder = new();
                _ = stringBuilder.Append(si).Append(si);
                for (int d = 1; i - 1 - d >= 0 && i + d < s.Length; d++)
                {
                    char c = s[i - 1 - d];
                    if (c == s[i + d])
                    {
                        _ = stringBuilder.Insert(0, c).Append(c);
                    }
                    else
                        break;
                }
                result = result.Length > stringBuilder.Length ? result : stringBuilder;
            }
        }
        return result.ToString();
    }
}